#include "domainquerydlg.h"
#include "ui_domainquerydlg.h"
#include "clientsocket.h"
#include "tdomain.h"
//#include <QMessageBox>
//#include <QThread>
#include "customdomaincreatedlg.h"
//#include <QFileDialog>
//#include <QStandardPaths>
#include "global.h"
#include "xlsxdocument.h"
#include "xlsxworksheet.h"

DomainQueryDlg::DomainQueryDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DomainQueryDlg)
{

    ui->setupUi(this);
    m_tDomain = static_cast<TDomain *>(QWidget::parentWidget());
    initUI();
    initModel();
}

DomainQueryDlg::~DomainQueryDlg()
{
    delete ui;
}

void DomainQueryDlg::initUI()
{
    //m_tableView = new QTableView(this);
    m_tableModel = new QStandardItemModel;
    m_strColsName<<"域名"<<"后缀"<<"注册状态"<<"注册商名称"<<"创建时间"<<"过期时间"<<"更新时间"<<"DNS服务器"<<"所有人名称"<<"所有人组织"<<"所有人国家"<<"所有人邮箱"<<"域名状态";
    ui->tbv_dnInfo->setSelectionBehavior(QAbstractItemView::SelectRows);//行选中
    ui->tbv_dnInfo->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    // m_tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {/*background-color:#1E90FF;*/font:10pt '微软雅黑';}");//标题栏样式
    ui->tbv_dnInfo->horizontalHeader()->setFixedHeight(35);//标题栏行高
    ui->tbv_dnInfo->verticalHeader()->setDefaultSectionSize(25);//设置列的行高
    m_tableModel->setHorizontalHeaderLabels(m_strColsName);

    m_headerCheckbox = new QCheckBox("", ui->tbv_dnInfo->horizontalHeader());
    m_headerCheckbox->setStyleSheet("margin-left: 3px; margin-top: 10px;");
    // 创建并配置过滤代理模型
    m_proxyModel = new MultiColumnFilterProxyModel();
    m_proxyModel->setSourceModel(m_tableModel);
    // 创建QTableView并设置代理模型
    ui->tbv_dnInfo->setModel(m_proxyModel);
    ui->lb_success->setText("成功："+QString::number(0));
    ui->lb_fail->setText("失败："+QString::number(0));
    ui->lb_total->setText("总数："+QString::number(0));
    ui->tbv_dnInfo->setMouseTracking(true);
connect(ui->tbv_dnInfo, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(slotRowDoubleClicked(const QModelIndex &)));
    connect(ui->tbv_dnInfo,SIGNAL(entered(QModelIndex)),this,SLOT(slotShowToolTip(QModelIndex)));

// 表头全选复选框实现全选/全不选
connect(m_headerCheckbox, &QCheckBox::stateChanged, this, [&](int state) {
    toggleSelectAll(state == Qt::Checked);
});
}

void DomainQueryDlg::initModel()
{


//    m_DnListStr.append("abc.com");
//    m_DnListStr.append("abc.cn");
//    m_DnListStr.append("abc.org");
//    m_DnListStr.append("abc.net");
//    m_DnListStr.append("abc.biz");
//    m_DnListStr.append("halo.com");
//    m_DnListStr.append("halo.cn");
//    m_DnListStr.append("halo.org");
//    m_DnListStr.append("halo.biz");
//    m_DnListStr.append("halo.net");

//    for (const QString str : m_DnListStr) {
//        QList<QStandardItem*> rowItems;
//        //rowItems.append(new QStandardItem(QString::number(1)));
//        rowItems.append(new QStandardItem(str));
//        rowItems.append(new QStandardItem(str.section('.',1,-1)));
//        rowItems.append(new QStandardItem("-"));
//        rowItems.append(new QStandardItem("-"));
//        rowItems.append(new QStandardItem("-"));
//        rowItems.append(new QStandardItem("-"));
//        rowItems.append(new QStandardItem("-"));
//        rowItems.append(new QStandardItem("-"));
//        //rowItems.append(new QStandardItem("-"));
//        m_tableModel->appendRow(rowItems);
//    }
}

void DomainQueryDlg::queryDomainWhois(QString dnStr)
{
    QString suffix = dnStr.section('.',1,-1);
    QString addrStr;
    int port;
    //qDebug()<<suffix;
    QStringList strWhois = g_dnSuffixMappingWhoIs["."+suffix];
    if(strWhois.size()==0)
    {
        qDebug()<<"无法查找到匹配的域名服务器!"<<dnStr;
        return;
    }
//
//    for(int i=0;i<m_tDomain->m_suffixQryAddr.size();i++)
//    {
//        str=m_tDomain->m_suffixQryAddr.at(i).domainSuffix;
//        //qDebug()<<str;
//        if(suffix==str)
//        {
//            addrStr=m_tDomain->m_suffixQryAddr.at(i).qryAddress;
//            port=m_tDomain->m_suffixQryAddr.at(i).port;
//            //qDebug()<<addrStr<<port;
//            break;
//        }
//    }
//    if(addrStr.length()==0)
//    {
//        qDebug()<<"无法查找到匹配的域名服务器!"<<dnStr;
//        return;
//    }

    addrStr=strWhois.at(0);
    port = strWhois.at(1).toInt();
    qDebug()<<"发送查询请求"<<addrStr<<port<<dnStr;

    ClientSocket *clientSocket = new ClientSocket();
    clientSocket->m_sendMsg = dnStr;
    clientSocket->m_flag = dnStr;
    QThread *socketThread = new QThread;

    clientSocket->moveToThread(socketThread);

    connect(socketThread, &QThread::started, clientSocket, [=](){clientSocket->startConnection(addrStr,port);});
    connect(socketThread, &QThread::finished, socketThread, &QThread::deleteLater);
    connect(socketThread, &QThread::finished, clientSocket, &QObject::deleteLater);

    connect(clientSocket, &QObject::destroyed, socketThread, &QThread::quit);
    // connect(clientSocket, &ClientSocket::socketError, this, [](QAbstractSocket::SocketError error) { /* 错误处理 */ });

    connect(clientSocket, &ClientSocket::dataReceived, this, &DomainQueryDlg::dealRecvDataFromServer);
    socketThread->start();
}

bool DomainQueryDlg::decodeWhoisInfoToMap(QString dnStr,QByteArray data,int row)
{
    QString suffix = dnStr.section('.',1,-1);
    QString separator,bufStr;
    bufStr = data;
    //qDebug()<<suffix;
    QStringList strWhois = g_dnSuffixMappingWhoIs["."+suffix];
    if(strWhois.size()==0)
    {
        qDebug()<<"无法查找到匹配的域名服务器!"<<dnStr;
        return false;
    }
    QMap<QString, QString> infoMaps;
    //清除DNSSEC: unsigned之后的无效数据
    int index = bufStr.indexOf("DNSSEC: unsigned");
    if(index==-1)
    {
        qDebug()<<"域名未注册,没有DNSSEC信息."<<dnStr<<strWhois.at(0);
        infoMaps["Regist Status"]="未注册";

    }
    else
    {
        if (index >= 0)
            bufStr = bufStr.left(index+16);

        if(strWhois.at(2)=="1")
            separator = "\r\n";
        else
            separator = "\n";
        //qDebug()<<bufStr;
        QStringList domainStrings = bufStr.split(separator);

        QVector<QString> statusVectors, nameServerVectors;
        QString sv,nsv;
        QString keystr, valstr;

        for (int i = 0; i < domainStrings.size(); i++) {
            //qDebug()<<domainStrings.at(i);

            QStringList infoStrings = domainStrings.at(i).split(": ");
            if(infoStrings.size()<1)
            {
                qDebug() << "接收数据异常: " << dnStr<<domainStrings.at(i);
                    return false;
            }
            keystr = infoStrings.at(0).trimmed();
            if(infoStrings.size()==2)
                valstr = infoStrings.at(1).left(127);
            else
                valstr="";
            if(valstr=="REDACTED FOR PRIVACY"||valstr.contains("Please query the WHOIS"))
                valstr="";

            if (keystr == "Domain Status") {
                statusVectors.append(valstr);
                QStringList astr = valstr.split(" ");
                sv+=astr.at(0);
                sv+=";";
                infoMaps[keystr]=sv;
            } else if (keystr == "Name Server") {
                nameServerVectors.append(valstr);
                nsv+=valstr;
                nsv+=";";
                infoMaps[keystr]=nsv;
            } else {
                infoMaps[keystr] = valstr;
            }
            //qDebug() << keystr << valstr;
            if (keystr.trimmed() == "DNSSEC")
                break;
        }
        infoMaps["Regist Status"]="已注册";
    }

    //qDebug() << "成功接收数据" << infoMaps.size()<<dnStr;//<<infoMaps;

    if(strWhois.at(2)=="1")//以/r/n分行
    {
        m_tableModel->item(row,2)->setText(infoMaps["Regist Status"]);
        m_tableModel->item(row,3)->setText(infoMaps["Registrar"]);//注册商名称
        m_tableModel->item(row,4)->setText(infoMaps["Creation Date"].left(10));//创建时间
        m_tableModel->item(row,5)->setText(infoMaps["Registry Expiry Date"].left(10));//过期时间
        m_tableModel->item(row,6)->setText(infoMaps["Updated Date"].left(10));//更新时间
        m_tableModel->item(row,7)->setText(infoMaps["Name Server"]);//DNS服务器
        m_tableModel->item(row,8)->setText(infoMaps["Registrant Name"]);//所有人名称
        m_tableModel->item(row,9)->setText(infoMaps["Registrant Organization"]);//所有人组织
        m_tableModel->item(row,10)->setText(infoMaps["Registrant Country"]);//所有人国家
        m_tableModel->item(row,11)->setText(infoMaps["Registrant Email"]);//所有人邮箱
        m_tableModel->item(row,12)->setText(infoMaps["Domain Status"]);//域名状态

    }
    else//以/n分行
    {
        m_tableModel->item(row,2)->setText(infoMaps["Regist Status"]);
        m_tableModel->item(row,3)->setText(infoMaps["Sponsoring Registrar"]);
        m_tableModel->item(row,4)->setText(infoMaps["Registration Time"].left(10));
        m_tableModel->item(row,5)->setText(infoMaps["Expiration Time"].left(10));
        m_tableModel->item(row,6)->setText(infoMaps["Expiration Time"].left(10));
        m_tableModel->item(row,7)->setText(infoMaps["Name Server"]);
        m_tableModel->item(row,8)->setText(infoMaps["Registrant"]);
        m_tableModel->item(row,9)->setText(infoMaps["Registrant Organization"]);//所有人组织
        m_tableModel->item(row,10)->setText(infoMaps["Registrant Country"]);//所有人国家
        m_tableModel->item(row,11)->setText(infoMaps["Registrant Email"]);//所有人邮箱
        m_tableModel->item(row,12)->setText(infoMaps["Domain Status"]);//域名状态

    }
    //"域名"<<"后缀"<<"注册状态"<<"注册商名称"<<"创建时间"<<"过期时间"<<"更新时间"<<"DNS服务器"<<"所有人名称"<<"所有人组织"<<"所有人国家"<<"所有人邮箱"<<"域名状态";
    return true;
}



void DomainQueryDlg::on_btn_import_clicked()
{
    QString m_strFileName = QFileDialog::getOpenFileName(this,"打开",QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),"TXT 文件(*.txt)");
    if(m_strFileName.isEmpty())
    {
        //QMessageBox::information(this,"提示","打开文件路径失败"+m_strFileName);
        return;
    }
    QFile *pFile = new QFile(m_strFileName);
    if(!pFile->open(QIODevice::ReadOnly))
    {
        QMessageBox::information(this,"提示","打开文件失败");
        return;
    }

    // 创建文本流对象，便于读取文件内容
    QTextStream in(pFile);
    // 初始化QStringList用于存放处理后的行
    QStringList trimmedLines;
    // 逐行读取文件内容
    while (!in.atEnd()) {
        QString line = in.readLine();
        if(!line.isEmpty())
        {
            if(line.endsWith('\r'))
                line.chop(1);
            if(line.endsWith('\n'))
                line.chop(1);
            line = line.trimmed();
            trimmedLines.append(line);
            //qDebug()<<line;
        }
    }
    pFile->close();

//    QByteArray array = pFile->readAll();
//    pFile->close();
//    QString content = array;
//    content = content.trimmed();//去掉头尾两端的空格
//    if (content.endsWith('\n')) {
//        content.chop(1); // 删除最后一个字符（假设是换行符）
//    }
//    if (content.endsWith('\r')) {
//        content.chop(1); // 删除最后一个字符（假设是换行符）
//    }
//    QStringList domainStrings = content.split("\n");
    if(trimmedLines.length())
    {

        processReceivedData(trimmedLines);
    }
}


void DomainQueryDlg::on_btn_dnQry_clicked()
{
//    const auto sourceModel = m_proxyModel->sourceModel();
//    for (int row = 0; row < m_proxyModel->rowCount(); ++row) {
//        for (int column = 0; column < m_proxyModel->columnCount(); ++column) {
//            QModelIndex proxyIndex = m_proxyModel->index(row, column);
//            QModelIndex sourceIndex = m_proxyModel->mapToSource(proxyIndex);

//            QVariant data = sourceModel->data(sourceIndex);
//            // 处理或存储数据（data）
//            qDebug()<<data;
//        }
//    }
    QStringList qryDnListStr;
    for (int row = 0; row < m_proxyModel->rowCount(); ++row) {
            QModelIndex proxyIndex = m_proxyModel->index(row, 0);
            QModelIndex sourceIndex = m_proxyModel->mapToSource(proxyIndex);
            if(m_tableModel->itemFromIndex(sourceIndex)->checkState()==Qt::Checked)
            {
                QVariant data = this->m_tableModel->data(sourceIndex);
            // 处理或存储数据（data）
                qryDnListStr.append(data.toString());
            }
    }
    m_totalNum = qryDnListStr.size();
    m_successNum =0;
    ui->lb_success->setText("成功："+QString::number(m_successNum));
    for (const QString str : qryDnListStr) {
        //    qDebug()<<str;
        queryDomainWhois(str);
        QThread::msleep(200);
    }
    //qDebug()<<"域名查询请求发送完成";
}

void DomainQueryDlg::dealRecvDataFromServer(QByteArray data,QString flag)
{
    //QMap<QString, QString> infoMaps;
    qDebug() << "收到服务端数据" << flag<<data.length();
    QList<QStandardItem*> foundLst = m_tableModel->findItems(flag, Qt::MatchExactly, 0);
    if(foundLst.size()<1)
    {
        qDebug() << "找不到指定的域名信息" << flag;
        return;
    }
    QStandardItem* item = foundLst.at(0);
    int row = item->row();
    if(!decodeWhoisInfoToMap(flag,data,row))
    {
        qDebug()<<"域名查询返回数据解析失败"<<flag<<data;
        return;
    }

    //qDebug()<<"接收成功" << foundLst.size()<<foundLst<<flag<<row<<item->text();

    m_successNum++;
    ui->lb_success->setText("成功："+QString::number(m_successNum));
    ui->lb_fail->setText("失败："+QString::number(m_totalNum-m_successNum));

}


void DomainQueryDlg::on_btn_create_clicked()
{
    QSize dialogSize = size();
    // 居中显示对话框
    QPoint centerPos = geometry().center() - QPoint(dialogSize.width() / 2, dialogSize.height() / 2+30);

    CustomDomainCreateDlg dlg(this);
    dlg.setWindowTitle("自定义域名创建");
    dlg.setFixedSize(dialogSize);
    dlg.move(centerPos);
    connect(&dlg, &CustomDomainCreateDlg::dataTransfer, this, [this](QStringList data) {processReceivedData(data);});
    dlg.exec();

}

void DomainQueryDlg::processReceivedData(QStringList data)
{

    //qDebug()<<data;
    //m_tableModel->clear();
    m_tableModel->removeRows(0,m_tableModel->rowCount());
    m_DnListStr=data;
    QStringList m_strsuffix;

    QString strsuffix;
    for (const QString str : m_DnListStr) {
        QList<QStandardItem*> rowItems;
        //rowItems.append(new QStandardItem(QString::number(1)));
        for(int i=0;i<m_strColsName.size();i++)
        {
            if(i==0)
            {
                QStandardItem *item = new QStandardItem(str);
                item->setCheckable(true);
                rowItems.append(item);
            }
            else if(i==1)
            {
                strsuffix = "."+str.section('.',1,-1);
                m_strsuffix.append(strsuffix);
                rowItems.append(new QStandardItem(strsuffix));
            }
            else
                rowItems.append(new QStandardItem("-"));
        }
        m_tableModel->appendRow(rowItems);
    }


    ui->lb_total->setText("总数："+QString::number(m_totalNum));
    QSet<QString> uniqueSet(m_strsuffix.begin(), m_strsuffix.end()); // 使用QSet去除重复项
    QStringList uniqueList(uniqueSet.begin(), uniqueSet.end()); // 将QSet转换回QStringList
    ui->cb_suffix->clear();
    ui->cb_suffix->addItem("无限制");
    ui->cb_suffix->addItems(uniqueList);
    if(m_headerCheckbox->checkState()!=Qt::Checked)
    {
        this->m_headerCheckbox->setChecked(true);
        m_totalNum = data.size();
    }
    else
        toggleSelectAll(true);
}


void DomainQueryDlg::on_btn_dnFilter_clicked()
{
/*
    QMap<int, QString> filterPatterns;

    QString filterStr;
    filterStr = ui->cb_dnStatus->currentText();
    if(filterStr!="无限制")
        filterPatterns[11]=filterStr;

    filterStr = ui->cb_regStatus->currentText();
    if(filterStr!="无限制")
        filterPatterns[2]=filterStr;

    filterStr = ui->cb_suffix->currentText();
    if(filterStr!="无限制")
        filterPatterns[1]=filterStr;

    filterStr = ui->cb_expDate->currentText();
    if(filterStr!="无限制")
        filterPatterns[4]=filterStr;

//根据列的索引设置key的值，后面以key值作为列的索引
    m_proxyModel->setFilterPatterns(filterPatterns);
 */
    QVector<QStringList>  filterPatterns;

    QString filterStr;
    filterStr = ui->cb_dnStatus->currentText();
    if(filterStr!="无限制")
    {
        QStringList qsl;
        qsl<<"11"<<filterStr<<"contains";//筛选第11列包含所选信息的记录
        filterPatterns.append(qsl);
    }

    filterStr = ui->cb_suffix->currentText();
    if(filterStr!="无限制")
    {
        QStringList qsl;
        qsl<<"1"<<filterStr<<"equal";//筛选第1列等于所选信息的记录
        filterPatterns.append(qsl);
    }

    filterStr = ui->cb_expDate->currentText();
    if(filterStr!="无限制")
    {
        QDate currentDate = QDate::currentDate();
        QString strDate;
        if(filterStr=="1周内"){
            strDate=currentDate.addDays(7).toString("yyyy-MM-dd");

        }else if(filterStr=="2周内"){
            strDate=currentDate.addDays(14).toString("yyyy-MM-dd");
        }else if(filterStr=="1个月内"){
            strDate=currentDate.addDays(30).toString("yyyy-MM-dd");
        }else if(filterStr=="3个月内"){
            strDate=currentDate.addDays(90).toString("yyyy-MM-dd");
        }else if(filterStr=="6个月内"){
            strDate=currentDate.addDays(180).toString("yyyy-MM-dd");
        }else{
            strDate=currentDate.toString("yyyy-MM-dd");
        }
        QStringList qsl;
        qsl<<"4"<<strDate<<"less";//筛选第4列小于所选信息的记录
        filterPatterns.append(qsl);
    }
    qDebug()<<filterPatterns.size();
    m_proxyModel->setFilterPattern(filterPatterns);
}


void DomainQueryDlg::on_btn_reset_clicked()
{
    QMap<int, QString> filterPatterns;
    QVector<QStringList> filterPattern;
    //m_proxyModel->setFilterPatterns(filterPatterns);
    m_proxyModel->setFilterPattern(filterPattern);
    ui->cb_dnStatus->setCurrentIndex(0);
    ui->cb_regStatus->setCurrentIndex(0);
    ui->cb_suffix->setCurrentIndex(0);
    ui->cb_expDate->setCurrentIndex(0);
}

void DomainQueryDlg::slotRowDoubleClicked(const QModelIndex index)
{
    QModelIndex selectedIndex = ui->tbv_dnInfo->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        return;
    }

    QStandardItem *itemId = m_tableModel->item(selectedIndex.row(),0);
    qDebug()<<itemId->text();
    //int recId = itemId->text().toInt();

//    DomainDetailInfo ddi = getDomainDetailInfoById(recId);

//    QSize mainWindowSize = this->m_tDomain->size();
//    QSize dialogSize = QSize(mainWindowSize.width() * 0.8, mainWindowSize.height() * 0.8);
//    DomainDetailInfoDlg dlg;
//    // 设置对话框的大小
//    dlg.setFixedSize(dialogSize);

//    // 居中显示对话框
//    QRect screenGeometry = this->m_tDomain->geometry();
//    QPoint centerPos = screenGeometry.center() - QPoint(dialogSize.width() / 2, dialogSize.height() / 2);
//    dlg.move(centerPos);
//    dlg.initDlgData(ddi);
    //    dlg.exec();
}

void DomainQueryDlg::slotShowToolTip(QModelIndex index)
{
    QToolTip::showText(QCursor::pos(),index.data().toString());
    return ;
}

void DomainQueryDlg::toggleSelectAll(bool checked)
{
    //qDebug()<<checked<<(m_headerCheckbox->checkState()==Qt::Checked);
    int totalRows = ui->tbv_dnInfo->model()->rowCount();
    if(checked)
        m_totalNum = totalRows;
    else
        m_totalNum=0;
    for (int row = 0; row < totalRows; ++row) {
        QModelIndex index = ui->tbv_dnInfo->model()->index(row, 0);
        ui->tbv_dnInfo->model()->setData(index, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
    }
}

void DomainQueryDlg::on_btn_delete_clicked()
{
    QString msg = "确认要删除这些记录？";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示",msg);
    if(result==QMessageBox::No)
    {
        return;
    }
    int totalRowCount = m_tableModel->rowCount();
    for (int i = totalRowCount - 1; i >= 0; --i) {
        QModelIndex index = m_tableModel->index(i, 0); // 假设勾选列位于第一列
        if (index.data(Qt::CheckStateRole).toInt() == Qt::Checked) {
            m_tableModel->removeRow(i);
        }
    }
}

void DomainQueryDlg::on_btn_collect_clicked()
{
    bool ret;
    QStringList domainStrings;
    QString cellText;
    int totalRowCount = m_tableModel->rowCount();
    for (int i = totalRowCount - 1; i >= 0; --i) {
        QModelIndex index = m_tableModel->index(i, 0); // 假设勾选列位于第一列
        if (index.data(Qt::CheckStateRole).toInt() == Qt::Checked) {
            cellText = index.data(Qt::DisplayRole).toString();
            domainStrings.append(cellText);
        }
    }
    int dnsize = domainStrings.size();
    int success =0;
    if(dnsize==0)
    {
        QMessageBox::information(this,"提示","请勾择要收藏的域名");
    }
    else
    {
        QString msg = "确认要收藏这"+QString::number(dnsize)+"条记录？";
        QMessageBox::StandardButton result= QMessageBox::question(this,"提示",msg);
        if(result==QMessageBox::No)
        {
            return;
        }
        for(int j=0;j<dnsize;j++)
        {
            cellText = domainStrings.at(j);
            if(!m_tDomain->m_dbMySql->insertDomainRecToSingleTables(g_undefineCategoryId,cellText))
            {
                success++;
            }
            else
            {
                qDebug()<<"收藏失败"+cellText<<g_undefineCategoryId;
            }
        }

        msg = "收藏成功,已收藏到主窗口\"未分类域名\"列表中,总数/记录数:"+QString::number(dnsize)+"/"+QString::number(success);
        QMessageBox::information(this,"提示",msg);
    }
}


void DomainQueryDlg::on_btn_export_clicked()
{
    QString filePath = QFileDialog::getSaveFileName(
        this,
        tr("Save as."),
        QString(),
        tr("Excel files (*.xlsx)")
        );

    if (!filePath.isEmpty()) {
        exportTableViewToExcel(ui->tbv_dnInfo, filePath);
    }
}


void DomainQueryDlg::on_btn_close_clicked()
{
    this->close();
}

void DomainQueryDlg::exportTableViewToExcel(QTableView *tableView, const QString &filePath)
{
    // 创建Excel工作簿对象
    QXlsx::Document workbook;

    // 获取QTableView的模型
    QAbstractItemModel* model = tableView->model();

    // 获取表头信息
    QStringList headerLabels;
    for (int column = 0; column < model->columnCount(); ++column) {
        headerLabels << model->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
    }
    qDebug()<<headerLabels;
    // 写入表头
    workbook.addSheet("Sheet1");
    QXlsx::Worksheet* sheet = dynamic_cast<QXlsx::Worksheet*>(workbook.sheet("Sheet1"));
    // 写入表头
    int currentRow = 1;//excel表格是从1行1列开始的
    for (const QString& label : headerLabels) {
        sheet->write(currentRow, headerLabels.indexOf(label)+1, label);
    }

    // 写入数据行
    //currentRow++;
    int rownum = model->rowCount();
    int clonum = model->columnCount();
    for (int row = 0; row <= rownum; row++) {
        for (int column = 0; column <= clonum; column++) {
            QString value = model->data(model->index(row, column), Qt::DisplayRole).toString();
            sheet->write(currentRow+1, column+1, value);//excel表格是从1行1列开始的
            //qDebug()<<row<<column<<value<<currentRow;
        }
        currentRow++;
    }

    // 保存到指定文件
    if(workbook.saveAs(filePath))
        QMessageBox::information(this,"提示","导出成功");
    else
        QMessageBox::information(this,"提示","导出失败");
}
